package net.result;

import com.opensymphony.xwork2.ActionInvocation;
import freemarker.template.Configuration;
import freemarker.template.Template;
import net.base.ToolsAction;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;

public class JsonFreemarkerResult extends BaseResult {
    private static final Log log = LogFactory.getLog(JsonFreemarkerResult.class);
    private String location;
    private String errorPage = "/commons/common/error.jsp";
    protected boolean isAjax=true;


    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getErrorPage() {
        return errorPage;
    }

    public void setErrorPage(String errorPage) {
        this.errorPage = errorPage;
    }

    public JsonFreemarkerResult() {
        // TODO Auto-generated constructor stub
        super();
    }

    public JsonFreemarkerResult(String location) {
        // TODO Auto-generated constructor stub
        super(location);
    }


    public void execute(ActionInvocation invocation) throws Exception {
        // TODO Auto-generated method stub
        long startTime = System.currentTimeMillis();
        ServletContext sc = ServletActionContext.getServletContext();
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        System.out.println("charset:" + request.getCharacterEncoding());
        response.setCharacterEncoding(request.getCharacterEncoding());
        response.setContentType("application/json;charset="+request.getCharacterEncoding());

        PrintWriter output = response.getWriter();
        ToolsAction baseAction = (ToolsAction) invocation.getAction();

        try
		{
			String viewName=request.getParameter("viewName")==null?this.location:request.getParameter("viewName");
            Configuration cfg = new Configuration();
            cfg.setServletContextForTemplateLoading(baseAction.getRequest().getSession().getServletContext(), "/");
            Template t = cfg.getTemplate(viewName,"UTF-8");
            StringWriter writer = new StringWriter();
            t.process(baseAction.getModel(), writer);

            String content=writer.toString();

            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.registerJsonValueProcessor(java.sql.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
            jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
            JSONObject js=JSONObject.fromObject(baseAction.getModel(),jsonConfig);
            js.put("code",new Integer(baseAction.getCode()));
            js.put("msg", baseAction.getMsg());
            js.put("expMsg", baseAction.getExpMsg());
            js.put("data", content.trim());
            content = js.toString();
            log.info(content);
            output.write(content);
            output.flush();
		}
		catch (Exception ex)
		{
            ex.printStackTrace();
			HashMap hashMap = new HashMap();
			hashMap.put("code", "-1");
			hashMap.put("type", "err");
			hashMap.put("msg","发生错误");
			hashMap.put("mx", ex.getMessage());


			JSONObject js = new JSONObject();
			js.put("msg", hashMap);
			output.write(js.toString());
		}
		finally
		{
			if (output != null)	output.close();
		}
        log.info("use time " + (System.currentTimeMillis() - startTime) + " ms");
    }

    protected void doExecute(String location, ActionInvocation invocation) throws Exception {
        // TODO Auto-generated method stub
        this.location = location;
        this.execute(invocation);
    }

}
